import { cloneDeep } from 'lodash-es'
import type { Team } from '@/types'

export interface Plan {
  date: string
  teams: Pick<Team, 'id' | 'name'>[]
}

export function usePlans(
  teams: Ref<Pick<Team, 'id' | 'name'>[]>,
  dates: Ref<string[]>,
  shiftsCount: Ref<number>,
) {
  const [plans, setPlans] = useShallowState<Plan[]>([])

  // 推导排班计划
  function derive(array: any[], n: number) {
    let prev: any[] = cloneDeep(array)
    const result: any[] = []
    result.push(prev)
    const length = array.length
    for (let i = 1; i < length; i++) {
      const temp = cloneDeep(prev)
      prev = [
        ...temp.slice(n),
        ...temp.slice(0, n),
      ]
      result.push(prev)
    }
    return result
  }

  function generate() {
    const results = derive(toValue(teams), unref(shiftsCount))
    // console.log('results of derive: ', results);
    const data = toValue(dates).map((v, i) => {
      return {
        date: v,
        teams: results[i] as Plan['teams'],
      }
    })
    setPlans(data)
  }

  watchEffect(() => {
    generate()
  })

  return {
    plans,
    setPlans,
  }
}
